import request from "@/utils/request";
import { encryption, encryptionBase64 } from "@/utils/util";
import qs from "qs";

const basicAuth =
  "Basic " + encryptionBase64(import.meta.env.VITE_OAUTH2_APP_CLIENT);

// 手机验证码登录
export function mobileLogin({ mobile, code }: Record<string, any>) {
  const form = {
    mobile: `APP-SMS@${mobile}`,
    code,
    grant_type: "mobile",
    scope: "server",
  };

  return request.post(
    {
      url: "/auth/oauth2/token?" + qs.stringify(form),
      header: {
        Authorization: basicAuth, //"mini:mini"
        "content-type": "application/x-www-form-urlencoded",
      },
    },
    { withToken: false },
  );
}

// 账号密码登录
export function accountLogin(data: Record<string, any>) {
  data.grant_type = "password";
  data.scope = "server";

  // 密码加密
  data.password = encryption(data.password, import.meta.env.VITE_PWD_ENC_KEY);

  return request.post(
    {
      url: "/admin/oauth2/token?" + qs.stringify(data),
      header: {
        Authorization: basicAuth,
        "content-type": "application/x-www-form-urlencoded",
      },
    },
    { withToken: false },
  );
}

// 微信小程序登录

export function mnpLogin(code: string) {
  const form = {
    mobile: `APP-MINI@${code}`,
    code: code,
    grant_type: "mobile",
    scope: "server",
  };

  return request.post(
    {
      url: "/auth/oauth2/token?" + qs.stringify(form),
      header: {
        Authorization: basicAuth, //"mini:mini"
        "content-type": "application/x-www-form-urlencoded",
      },
    },
    { withToken: false },
  );
}  

//发送验证码
export function send(data: Record<string, any>) {
  return request.post({ url: "/admin/common/verify/send", data });
}

//验证验证码
export function check(data: Record<string, any>) {
  return request.post({ url: "/admin/common/verify/check", data });
}

//忘记密码
export function forgetPassword(data: Record<string, any>) {
  return request.put({ url: "/admin/appuser/forget-password", data });
}

//注册
export function register(data: Record<string, any>) {
  return request.post({ url: "/admin/appuser/register", data });
}

//忘记密码
export function forgotPassword(data: Record<string, any>) {
  return request.post({ url: "/admin/appuser/edit", data });
}

//向微信请求code的链接
export function getWxCodeUrl() {
  return request.get({
    url: "/admin/login/oaCodeUrl",
    data: { url: location.href },
  });
}

// 公众号登录
export function OALogin() {
  return;
}

// 退出登录
export function accountLogout() {
  return request.delete({
    url: "/admin/token/logout",
  });
}
